package homework;

import java.io.*;
import java.net.URL;

public class XlassLoader extends ClassLoader {
    public static void main(String[] args) {
        try {
            // 加载类
            Class<?> clazz = loadXlass("Hello");
            //System.out.println(clazz);
            // 执行方法
            if (null != clazz) {
                clazz.getMethod("hello").invoke(clazz.newInstance());
            } else {
                System.out.println("类找不到");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 加载类
    public static Class<?> loadXlass(String fileName) throws IOException, InstantiationException, IllegalAccessException {
        Class<?> clazz = new XlassLoader().findClass(fileName);
        return clazz;
    }

    @Override
    protected Class<?> findClass(String fileName) {
        URL url = XlassLoader.getSystemClassLoader().getResource(fileName + ".xlass");
        //System.out.println("url = " + url);
        File file = new File(url.getPath());
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            int length = in.available();
            //System.out.println(length);
            byte[] byteArray = new byte[length];
            in.read(byteArray);
            byte[] classBytes = decode(byteArray);
            return defineClass(fileName, classBytes, 0, classBytes.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 解码 x=255-x
    private static byte[] decode(byte[] byteArray) {
        byte[] decodeArray = new byte[byteArray.length];
        for (int i = 0; i < byteArray.length; i++) {
            decodeArray[i] = (byte) (255 - byteArray[i]);
        }
        return decodeArray;
    }
}
